<template>
     <el-button v-on:click="openupdDialog(null,'add2'),drawer=true,str='添加一级菜单'">添加</el-button>
 <el-table
      :data="tableData1"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      default-expand
       :tree-props="{ children: 'children'}"
    >
      <el-table-column prop="name" label="分类名称" sortable />
      <el-table-column prop="level" label="分类级别" /> 
      <el-table-column prop="sort" label="排序号" />
      <el-table-column label="状态" width="70">
        <template #default="scope">
          <span v-if="scope.row.status === 1">
            <el-tag type="success">显示</el-tag>
          </span>
          <span v-else-if="scope.row.status === 0">
            <el-tag type="danger">隐藏</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="图标" width="100" heigth="100">
        <template #default="scope" >
                <el-image style="width: 100px; height: 50px" :src=scope.row.icon />
        </template>
      </el-table-column>
      <el-table-column label="操作">
          <template #default="scope">
              <el-dropdown placement="bottom">
                <el-button>操作</el-button>
                 <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-on:click="openupdDialog(scope.row,'upd'),drawer=true,str='修改信息'">编辑</el-dropdown-item>
                    <el-dropdown-item><span style="color: red;" v-on:click="del(scope.row);">删除</span></el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <span v-if="scope.row.level === '一级'||scope.row.level=='二级'">
               <el-button v-on:click="openupdDialog(scope.row,'add1'),drawer=true,str='添加'">添加</el-button>
              </span>
       
        
          </template>
      </el-table-column>  
    </el-table>
      <el-drawer v-model="drawer" title="I am the title" :with-header="false">
        <h2>{{ str }}</h2>
             <el-form :model="ruleForm" label-width="auto" style="max-width: 600px" :rules="rules">
                <el-form-item label="分类名称" prop="name">
                  <el-input v-model="ruleForm.name" />
                </el-form-item>
                <el-form-item label="排序" >
                   <el-input-number v-model="ruleForm.sort" :min="1" :max="10"/>    
                </el-form-item>          
                <el-form-item label="状态">
                  隐藏 &nbsp;<el-switch v-model="ruleForm.status" />&nbsp;显示
                </el-form-item>
                <el-form-item label="图标" >
                  <el-input v-model="ruleForm.icon" />
                </el-form-item>
          </el-form>
          <el-button v-on:click="opens(str),drawer=false">保存</el-button>
      </el-drawer>
</template>

<script lang="ts" setup>

import {ref,reactive,onMounted} from 'vue';
import axios  from 'axios';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'

const str=ref("");

interface Category {
  id: string;          
  name: string;
  level:string;
  parentId: string;
  icon: string;
  sort: number;
  status: number;
  is_deleted: string;
  update_time: string;
  children?: Category[]   
}
const ruleForm=ref( {
  name:"",
  sort:0,
  status:0,
  icon:"",
  id:"",
  parentId:"",
})
const drawer = ref(false)

const openupdDialog = (parent: Category,obj:string) => {
  if(obj=='upd'){
    ruleForm.value.name=parent.name;
    ruleForm.value.icon=parent.icon;
    ruleForm.value.sort=parent.sort;
    ruleForm.value.status=parent.status;
    ruleForm.value.id=parent.id;
    ruleForm.value.parentId=parent.parentId;
  }else if(obj=='add1'){
    add1(parent);
  }else if(obj=="add2")
    add2()
  
};

const opens = async(str:string)=>{
  if(str=="修改信息"){
    update();
  }else if(str=="添加"||str=="添加一级菜单"){
    adds();
  }
}

const tableData3 = reactive<Category[]>([])
const tableData1 = reactive<Category[]>([])
const tableData2 = reactive<Category[]>([])

const init =async()=>{
    tableData1.length=0;
    tableData2.length=0;
    tableData3.length=0;
    const {data}=await axios.get("/ktmall/api/category");
      
       
      const filterstr1 = data.data.filter((item: Category) => 
        item.parentId=="0"
      );

      const level1Ids = filterstr1.map(item => item.id); 
      console.log(level1Ids)
      const filterstr2 = data.data.filter((item: Category) =>
        level1Ids.includes(item.parentId)
      );

      const level2Ids = filterstr2.map(item => item.id); 
      const filterstr3 = data.data.filter((item: Category) => 
        level2Ids.includes(item.parentId) 
      );
     
        tableData1.push(...filterstr1);
        tableData3.push(...filterstr3);
        tableData2.push(...filterstr2);
       
        console.log(tableData3)
        tableData1.forEach(item => item.level = "一级");
        tableData2.forEach(item => item.level = "二级");
        tableData3.forEach(item => item.level = "三级");

        tableData1.forEach(parent => {
            parent.children = tableData2.filter(child => child.parentId === parent.id);
        });
        tableData2.forEach(parent => {
            parent.children = tableData3.filter(child => child.parentId === parent.id);
        });
        console.log(tableData1)
     console.log(tableData2)
     console.log(tableData3)
};


onMounted(() => {
  init();
});



const del=async(row:Category)=>{
  if(row.children?.length>0){
    open();
    return;
  }
      const {data} = await axios.delete("/ktmall/api/category/"+row.id);
      console.log(data)
      if(data.msg=="操作成功！"){
        open1();
        init();
      }
      
}





const update=async()=>{
  const {data} = await axios.post("/ktmall/api/category/",ruleForm.value)
  console.log(data)
  init();
}


const add1 = async (parent: Category) => {
 
  let childrenList: Category[] = [];
  let parentid = "";
   if (parent.level === "一级") {
    childrenList = tableData2.filter(child => child.parentId === parent.id);
      parentid=parent.id;

  } else if (parent.level === "二级") {
    childrenList = tableData3.filter(child => child.parentId === parent.id);
      parentid=parent.id;
  
  } 
  console.log(parentid)
  const sortNumbers = childrenList.map(child => Number(child.sort) || 0);
  const maxSort = Math.max(...sortNumbers)
  ruleForm.value.icon="";
  ruleForm.value.id="";
  ruleForm.value.name="";
  ruleForm.value.sort=maxSort+1;
  ruleForm.value.status=1
  ruleForm.value.parentId=parentid;
}

const adds = async()=>{
  ruleForm.value.id=null;
  console.log(ruleForm.value);
  const {data} = await axios.post("/ktmall/api/category/",ruleForm.value)
  console.log(data)
  init();
}


const add2 = () => {
  const levelSort = tableData1.map(item => item.sort);
  console.log(levelSort)
  const maxSort = Math.max(...levelSort)
  ruleForm.value = {
    name: "",
    icon: "",
    id: "", 
    sort: maxSort + 1, 
    status: 1, 
    parentId: "0" 
  };
};



const open = () => {
  ElMessage.error('请先删除所有的子类')
}
const open1 = () => {
  ElMessage.success('删除成功')
}

const rules = reactive<FormRules<Category>>({
    name: [
        { required: true, message: '分类名称不能为空', trigger: 'blur' },
  ]
})
</script>